# -*- coding: utf-8 -*-
"""
视频合成器 - 音视频合成
"""

import subprocess
import shutil
from pathlib import Path


try:
    from imageio_ffmpeg import get_ffmpeg_exe
except Exception:
    def get_ffmpeg_exe():
        return "ffmpeg"


class VideoComposer:
    """视频合成器"""

    def __init__(self):
        """初始化合成器"""
        self.ffmpeg = get_ffmpeg_exe()

    def compose(
        self,
        video_path: Path,
        audio_path: Path,
        output_path: Path,
        srt_path: Path = None,
        embed_subs: bool = False,
        burn_subs: bool = False,
        fps: int = 30,
    ) -> None:
        """
        合成音视频

        Args:
            video_path: 视频文件路径
            audio_path: 音频文件路径
            output_path: 输出文件路径
            srt_path: 字幕文件路径
            embed_subs: 嵌入字幕
            burn_subs: 烧录字幕
            fps: 帧率
        """
        output_path.parent.mkdir(parents=True, exist_ok=True)

        if burn_subs and srt_path and srt_path.exists():
            # 硬烧录字幕
            cmd = [
                self.ffmpeg, "-y",
                "-i", str(video_path),
                "-i", str(audio_path),
                "-vf", f"subtitles={str(srt_path.resolve())}",
                "-pix_fmt", "yuv420p",
                "-c:v", "libx264",
                "-c:a", "aac",
                "-shortest",
                str(output_path),
            ]
        elif embed_subs and srt_path and srt_path.exists():
            # 软嵌入字幕
            cmd = [
                self.ffmpeg, "-y",
                "-i", str(video_path),
                "-i", str(audio_path),
                "-i", str(srt_path),
                "-map", "0:v:0",
                "-map", "1:a:0",
                "-map", "2:0",
                "-c:v", "copy",
                "-c:a", "aac",
                "-c:s", "mov_text",
                "-metadata:s:s:0", "language=chi",
                "-shortest",
                str(output_path),
            ]
        else:
            # 简单合成
            cmd = [
                self.ffmpeg, "-y",
                "-i", str(video_path),
                "-i", str(audio_path),
                "-c:v", "copy",
                "-c:a", "aac",
                "-shortest",
                str(output_path),
            ]

        subprocess.run(cmd, check=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
